package pw.goyd.game.handler.imp;

import pw.goyd.game.api.DBDone;
import pw.goyd.game.constant.setting.GameSetting;
import pw.goyd.game.handler.Handler;
import pw.goyd.game.logic.ExchangeDiamondResponse;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.LoginList;
import pw.goyd.protocol.model.Response;
import pw.goyd.subscribe.PlayerCustomer;

/**
 * 金币兑换
 * Created by StanWind on 2016/11/4.
 */
public class EXCHANGEDIAMOND extends Handler implements GameSetting {
    @Override
    public void handle() {
        PlayerCustomer p = LoginList.getPlayer(ctx.getChannel().getId());
        if (p == null) {
            Log.getLogger().error("空指针--->ChannelID[" + ctx.getChannel().getId() + "]");
            return;
        }

        ExchangeDiamondResponse exchangeDiamondResponse = new ExchangeDiamondResponse();
        exchangeDiamondResponse.setPlayer(p);                                   //  设置兑换玩家
        //兑换金币开始
        if (p.getDiamond() < EXCHANGE_COUNT) {                                  //  钻石不足单次兑换
            exchangeDiamondResponse.setExchangeState(1);                        //  状态为失败
        } else {
            p.setDiamond(p.getDiamond() - EXCHANGE_COUNT);                      //  减少钻石
            p.setGold(p.getGold() + EXCHANGE_PROPORTION * EXCHANGE_COUNT);      //  增加金币
            DBDone.updatePlayer(p);                                             //  存储
            exchangeDiamondResponse.setExchangeState(0);                        //  状态为成功
            Log.getLogger().info("玩家[" + p.getNickname() + "] 兑换 " + EXCHANGE_COUNT + " 钻石");
        }
        Response response = new Response();
        response.setData(exchangeDiamondResponse.getBytes());
        response.setTime(0);
        response.setCmd(CMD_EXCHANGEDIAMOND);
        this.getCtx().getChannel().write(response);
    }
}
